package org.ehe.business.bom.controller;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.business.bom.domain.BomStructureTemp;
import org.ehe.business.bom.domain.bo.BomStructureTempBo;
import org.ehe.business.bom.domain.vo.BomStructureTempVo;
import org.ehe.business.bom.service.BomExcelImportService;
import org.ehe.business.bom.service.BomStructureTempService;
import org.ehe.business.bom.service.ExcelTemplateService;
import org.ehe.business.drawing.domain.dto.DesignDrawingDTO;
import org.ehe.common.core.domain.R;
import org.ehe.common.core.exception.ServiceException;
import org.ehe.common.log.annotation.Log;
import org.ehe.common.log.enums.BusinessType;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.common.satoken.utils.LoginHelper;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 物料上传中转
 * @author :zhangnn
 * @className :BomStructureTempController
 * @description: TODO
 * @date 2025-09-03 17:38:43
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/bom/structure/temp")
public class BomStructureTempController {

    private final BomExcelImportService bomExcelImportService;
    private final BomStructureTempService tempService;
    private final ExcelTemplateService excelTemplateService;

    /**
     * 导入Excel文件到BOM
     *
     * @param file Excel文件
     * @param importId 10位随机数字
     * @return 导入结果
     */
    @PostMapping("/excel")
    public R<Void> importExcel(@RequestParam("file") MultipartFile file,
                               @RequestParam("importId") Long importId) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return R.fail("上传文件不能为空");
            }
            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsm"))) {
                return R.fail("请上传Excel文件(.xlsx、.xls、.xlsm格式)");
            }

            // 验证BOM版本ID
            if (importId == null) {
                return R.fail("BOMID不能为空");
            }
            // 执行导入
            bomExcelImportService.importExcelToBom(file, importId);
            return R.ok("导入成功");
        } catch (Exception e) {
            log.error("导入Excel文件失败", e);
            return R.fail("导入失败：" + e.getMessage());
        }
    }

    /**
     * 下载导入模板
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        String tenantId = LoginHelper.getTenantId();
        try {
            log.info("开始生成Excel模板，tenantId: {}", tenantId);
            String fileName = String.format("物料管理模板-%d.xlsm", System.currentTimeMillis());
            excelTemplateService.generateExcelTemplate(response, fileName);
            log.info("Excel模板生成完成");
        } catch (Exception e) {
            log.error("下载模板失败，tenantId: {}", tenantId, e);

            // 确保响应没有被提交才能设置错误状态
            if (!response.isCommitted()) {
                response.reset();
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.setContentType("application/json;charset=UTF-8");
                try {
                    response.getWriter().write("{\"error\":\"模板生成失败\",\"message\":\"" + e.getMessage() + "\"}");
                } catch (IOException ioException) {
                    log.error("写入错误响应失败", ioException);
                }
            }
        }
    }

    /**
     * 查询上传中转信息
     * @param bo
     * @param pageQuery
     * @return
     */
    @GetMapping("/page")
    public TableDataInfo<BomStructureTempVo> tempPage(BomStructureTempBo bo, PageQuery pageQuery) {
        log.info("BOM分页查询请求: BomVersionId={}", bo.getBomVersionId());

        try {
            return tempService.queryList(bo, pageQuery);
        } catch (Exception e) {
            log.error("BOM分页查询失败", e);
            throw new ServiceException("BOM分页查询失败: " + e.getMessage());
        }
    }

    /**
     * 新增
     * @param dto
     * @return
     */
    @PostMapping("/add")
    public R<Integer> addStructure(@Valid @RequestBody BomStructureTemp dto) {
        int id = tempService.addStructure(dto);
        return R.ok(id);
    }

    /**
     * 修改
     * @param dto
     * @return
     */
    @PostMapping("/edit")
    public R<Integer> editStructure(@Valid @RequestBody BomStructureTemp dto) {
        Integer result = tempService.editStructure(dto);
        return R.ok(result);
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    public R<Integer> deleteStructure(@PathVariable Long id) {
        Integer result = tempService.deleteStructure(id);
        return R.ok(result);
    }
}
